package com.arunsawad.ilertu.activity;

import java.io.StringReader;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.arunsawad.ilertu.R;
import com.arunsawad.ilertu.common.AsyncActivity;
import com.arunsawad.ilertu.common.Constants;
import com.arunsawad.ilertu.common.LoadImageTask;
import com.arunsawad.ilertu.common.RequestTask;
import com.arunsawad.ilertu.common.Validator;

public class AddService extends Activity implements AsyncActivity {
	SharedPreferences preferences;
	ProgressDialog bar;
	String serviceId = null;
	String layoutCode = null;
	TextView txtViewName;
	TextView txtViewDesc;
	TextView txtViewField1;
	TextView txtViewField2;
	EditText txtField1;
	EditText txtField2;
	private static final int GET_SERVICE = 0; // flag
	private static final int ADD_SERVICE = 1; // flag
	int currentAction;
	AlertDialog.Builder alertDialogBuilder;
	AlertDialog alert;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.act_addservice);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,
				R.layout.title2_imgbtn_txt_btn);

		initTitle();

		preferences = getSharedPreferences(Constants.PREF_FILE, MODE_PRIVATE);

		Validator.Validate(this, preferences);

		Bundle extras = getIntent().getExtras();
		if (extras != null) {
			serviceId = extras.getString("serviceId");
		}
		LoadContent();
	}

	public void initTitle() {
		ImageButton imgBtn1 = (ImageButton) findViewById(R.id.title2_imgBtn1);
		imgBtn1.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent(getApplicationContext(), Home.class);
				startActivity(intent);
			}
		});

		TextView txtTitle = (TextView) findViewById(R.id.title2_txtTitle);
		txtTitle.setText(getString(R.string.add_service));

		Button btn = (Button) findViewById(R.id.title2_btn);
		btn.setText(getString(R.string.add));
		btn.setOnClickListener(new View.OnClickListener() {
			public void onClick(View v) {
				addService();
			}
		});
	}

	public void LoadContent() {
		// show progress bar
		bar = new ProgressDialog(AddService.this);
		bar.setIndeterminate(true);
		bar.show();

		String filter = "<service id=\"" + serviceId + "\"/>";
		String msg = String.format(Constants.MSG, "ilertu.services-get",
				preferences.getString(Constants.PREF_USER_NAME, ""),
				preferences.getString(Constants.PREF_PASSWORD, ""),
				preferences.getString(Constants.PREF_LANGUAGE, "en"), filter);

		currentAction = GET_SERVICE;
		RequestTask task = new RequestTask();
		task.setListener(this);
		task.execute(Constants.URL_GET_SERVICE, msg);
	}

	public void addService() {
		bar = new ProgressDialog(AddService.this);
		bar.setIndeterminate(true);
		bar.show();

		Boolean passed = true;
		String field1 = "";
		String field2 = "";
		if (layoutCode.equals("1")) {
			txtField1 = (EditText) findViewById(R.id.addservice_txtField1);
			txtField2 = (EditText) findViewById(R.id.addservice_txtField2);
			field1 = txtField1.getText().toString();
			field2 = txtField2.getText().toString();
			if (field1.equals("") || field2.equals(""))
				passed = false;
		} else {
			if (layoutCode.equals("2")) {
				txtField1 = (EditText) findViewById(R.id.addservice_txtField1);
				field1 = txtField1.getText().toString();
				if (field1.equals(""))
					passed = false;
			}
		}
		if (passed) {
			String filter = "<service id=\"" + serviceId + "\">";
			filter += "<inputField1>" + field1 + "</inputField1>";
			filter += "<inputField2>" + field2 + "</inputField2>";
			filter += "</service>";

			String msg = String.format(Constants.MSG,
					"ilertu.user.services-add",
					preferences.getString(Constants.PREF_USER_NAME, ""),
					preferences.getString(Constants.PREF_PASSWORD, ""),
					preferences.getString(Constants.PREF_LANGUAGE, "en"),filter);

			currentAction = ADD_SERVICE;
			RequestTask task = new RequestTask();
			task.setListener(this);
			task.execute(Constants.URL_ADD_SERVICE, msg);
		} else {
			alertDialogBuilder = new AlertDialog.Builder(this);
			alertDialogBuilder
					.setMessage(R.string.input_service_details)
					.setCancelable(false)
					.setPositiveButton(R.string.ok,
							new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog,
										int id) {
									bar.hide();
									dialog.cancel();
								}
							});
			alert = alertDialogBuilder.create();
			alert.show();
		}
	}

	@Override
	public void onRequestCompleted(String results) {
		if (results != null) {
			DocumentBuilderFactory factory = DocumentBuilderFactory
					.newInstance();
			DocumentBuilder builder;
			try {
				builder = factory.newDocumentBuilder();
				Document document = builder.parse(new InputSource(
						new StringReader(results)));
				NodeList nodes = document.getElementsByTagName("service");

				if (nodes.getLength() > 0) {
					Element e = (Element) nodes.item(0);
					if (currentAction == ADD_SERVICE) {
						String responseStatus = e
								.getElementsByTagName("responseStatus").item(0)
								.getTextContent();
						int messageId;
						if (responseStatus.equals("0")) {
							messageId = R.string.service_added;
						} else {
							if (responseStatus.equals("1")) {
								messageId = R.string.service_accepted;
							} else {
								messageId = R.string.service_rejected;
							}
						}
						alertDialogBuilder = new AlertDialog.Builder(this);
						alertDialogBuilder
								.setMessage(messageId)
								.setCancelable(false)
								.setPositiveButton(R.string.ok,
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
												Intent intent = new Intent(
														getApplicationContext(),
														RegisteredServices.class);
												startActivity(intent);
											}
										});
						alert = alertDialogBuilder.create();
						alert.show();
					} else {
						String name = e.getElementsByTagName("name").item(0)
								.getTextContent();
						String desc = e.getElementsByTagName("desc").item(0)
								.getTextContent();
						String imageUrl = e.getElementsByTagName("imageUrl")
								.item(0).getTextContent();
						layoutCode = e.getElementsByTagName("layoutCode")
								.item(0).getTextContent();

						txtViewName = (TextView) findViewById(R.id.addservice_txtViewName);
						txtViewName.setText(name);
						txtViewDesc = (TextView) findViewById(R.id.addservice_txtViewDesc);
						txtViewDesc.setText(desc);
						ImageView serviceImage = (ImageView) findViewById(R.id.addservice_image);
						serviceImage.setTag(imageUrl);
						LoadImageTask loadImageTask = new LoadImageTask();
						loadImageTask.execute(serviceImage);

						if (layoutCode.equals("1")) {
							txtViewField1 = (TextView) findViewById(R.id.addservice_txtViewField1);
							txtViewField2 = (TextView) findViewById(R.id.addservice_txtViewField2);
							txtField1 = (EditText) findViewById(R.id.addservice_txtField1);
							txtField2 = (EditText) findViewById(R.id.addservice_txtField2);
							txtViewField1.setVisibility(View.VISIBLE);
							txtViewField2.setVisibility(View.VISIBLE);
							txtField1.setVisibility(View.VISIBLE);
							txtField2.setVisibility(View.VISIBLE);
						} else {
							if (layoutCode.equals("2")) {
								txtViewField1 = (TextView) findViewById(R.id.addservice_txtViewField1);
								txtField1 = (EditText) findViewById(R.id.addservice_txtField1);
								txtViewField1.setText(R.string.hn_no);
								txtViewField1.setVisibility(View.VISIBLE);
								txtField1.setVisibility(View.VISIBLE);
							}
						}
					}
				} else {
					nodes = document.getElementsByTagName("error");
					if (nodes.getLength() > 0) {
						Element e = (Element) nodes.item(0);

						String errorMessage = e
								.getElementsByTagName("errorDesc").item(0)
								.getTextContent();

						alertDialogBuilder = new AlertDialog.Builder(this);
						alertDialogBuilder
								.setMessage(errorMessage)
								.setCancelable(false)
								.setPositiveButton(R.string.ok,
										new DialogInterface.OnClickListener() {
											public void onClick(
													DialogInterface dialog,
													int id) {
												dialog.cancel();
											}
										});
						alert = alertDialogBuilder.create();
						alert.show();
					}
				}

				// hide progress bar
				bar.hide();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
}